<?php
class Default_Model_AdvertisementMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Default_Model_DbTable_Advertisement');
        }
        
        return $this->_dbTable;
    }

	public function fetchAll($query, $option) {
		if ($query === NULL) {
			$resultSet = $this->getDbTable()->fetchAll();
		} else {
			$table = $this->getDbTable();
			$select = $table->select();
			$select->from($table)->where($query);
			$resultSet = $this->getDbTable()->fetchAll($select);
		}
		
		return $this->processResultSet($resultSet->toArray(), $option);
	}
	
	private function processResultSet($resultSet, $option) {
		$entries = array();
		
		if ($option == 'view') {
			foreach ($resultSet as $row) {
				$entry = new Default_Model_TableColumn_Advertisement($row);
				$entries[] = $entry;
			}
		} else {
			foreach ($resultSet as $row) {
				$entries[] = $row;
			}
		}
		
		return $entries;
	}
	
	public function fetchBy($page, $position) {
		$table = $this->getDbTable();
		$select = $table->select();
		$select->from($table);
		$select->where('page_id = ?', $page);
		$select->where('vi_tri = ?', $position);
		$select->where('ngay_het_han > ?', date('Y-m-d'));
		$select->order('uu_tien desc');
		$select->order('ngay_tao desc');
		return $this->processResultSet($table->fetchAll($select)->toArray(), 'view');
	}

}
?>